import http from 'k6/http';
import { check, sleep } from 'k6';
import { Rate } from 'k6/metrics';

// 自定义指标
const errorRate = new Rate('errors');

// 测试配置
export const options = {
  stages: [
    { duration: '30s', target: 10 }, // 30秒内逐渐增加到10个虚拟用户
    { duration: '1m', target: 20 },  // 1分钟内增加到20个虚拟用户
    { duration: '2m', target: 20 },  // 保持20个虚拟用户2分钟
    { duration: '30s', target: 0 },  // 30秒内减少到0个虚拟用户
  ],
  thresholds: {
    http_req_duration: ['p(95)<500'], // 95%的请求响应时间小于500ms
    http_req_failed: ['rate<0.1'],    // 失败率小于10%
    errors: ['rate<0.1'],             // 错误率小于10%
  },
};

// 基础URL配置
const BASE_URL = 'http://localhost:8081/api';

// 测试数据
const TEST_USERS = {
  teacher: {
    account: 'teacher001',
    password: 'teacher123'
  },
  student: {
    account: 'student001', 
    password: 'student123'
  }
};

// 生成随机用户数据用于注册测试
function generateRandomUser() {
  const timestamp = Date.now();
  const randomId = Math.floor(Math.random() * 10000);
  const userAccount = `testuser${timestamp}${randomId}`;
  return {
    userName: `测试用户_${timestamp}_${randomId}`,
    userAccount: userAccount,
    userPassword: 'test123456'
  };
}

// 生成随机课程数据用于创建课程测试
function generateRandomCourse() {
  const timestamp = Date.now();
  const randomId = Math.floor(Math.random() * 10000);
  const courseId = `COURSE${timestamp}${randomId}`;
  
  const subjects = ['数学', '物理', '化学', '生物', '计算机科学', '英语', '历史', '地理'];
  const methods = ['期末考试', '平时作业+期末考试', '项目答辩', '论文+答辩', '实验报告+考试'];
  
  const subject = subjects[Math.floor(Math.random() * subjects.length)];
  const method = methods[Math.floor(Math.random() * methods.length)];
  
  return {
    courseId: courseId,
    courseName: `${subject}基础课程_${randomId}`,
    course: `这是一门关于${subject}的基础课程，涵盖核心理论知识和实践应用。`,
    teachingGoal: `通过本课程学习，学生将掌握${subject}的基本概念和应用方法。`,
    examinationMethod: method
  };
}

// 用户登录测试
function testUserLogin() {
  const users = [TEST_USERS.teacher, TEST_USERS.student];
  const user = users[Math.floor(Math.random() * users.length)];
  
  const loginPayload = `account=${user.account}&password=${user.password}`;

  const loginResponse = http.post(`${BASE_URL}/users/login`, loginPayload, {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
  });

  const loginSuccess = check(loginResponse, {
    '登录状态码为200': (r) => r.status === 200,
    '登录响应时间 < 500ms': (r) => r.timings.duration < 500,
    '返回用户信息': (r) => {
      try {
        const body = JSON.parse(r.body);
        return body && body.userId;
      } catch (e) {
        return false;
      }
    },
  });

  if (!loginSuccess) {
    errorRate.add(1);
    console.log(`登录失败: ${user.account}, 状态码: ${loginResponse.status}, 响应: ${loginResponse.body}`);
  } else {
    errorRate.add(0);
  }

  return loginResponse;
}

// 获取所有课程测试
function testGetAllCourses() {
  const coursesResponse = http.get(`${BASE_URL}/courses`);

  const coursesSuccess = check(coursesResponse, {
    '获取课程状态码为200': (r) => r.status === 200,
    '获取课程响应时间 < 300ms': (r) => r.timings.duration < 300,
    '返回课程列表': (r) => {
      try {
        const body = JSON.parse(r.body);
        return Array.isArray(body);
      } catch (e) {
        return false;
      }
    },
  });

  if (!coursesSuccess) {
    errorRate.add(1);
    console.log(`获取课程失败, 状态码: ${coursesResponse.status}, 响应: ${coursesResponse.body}`);
  } else {
    errorRate.add(0);
  }

  return coursesResponse;
}

// 用户注册测试
function testUserRegister() {
  const newUser = generateRandomUser();
  
  const registerResponse = http.post(`${BASE_URL}/users/register`, JSON.stringify(newUser), {
    headers: {
      'Content-Type': 'application/json',
    },
  });

  const registerSuccess = check(registerResponse, {
    '注册状态码为200或409': (r) => r.status === 200 || r.status === 409, // 409表示用户已存在
    '注册响应时间 < 800ms': (r) => r.timings.duration < 800,
    '注册响应有效': (r) => {
      if (r.status === 200) {
        try {
          const body = JSON.parse(r.body);
          return body && body.userId;
        } catch (e) {
          return false;
        }
      } else if (r.status === 409) {
        return r.body.includes('用户已存在');
      }
      return false;
    },
  });

  if (!registerSuccess) {
    errorRate.add(1);
    console.log(`注册失败: ${newUser.userId}, 状态码: ${registerResponse.status}, 响应: ${registerResponse.body}`);
  } else {
    errorRate.add(0);
  }

  return registerResponse;
}

// 创建课程测试
function testCreateCourse() {
  // 首先登录获取用户ID
  const loginPayload = `account=${TEST_USERS.teacher.account}&password=${TEST_USERS.teacher.password}`;

  const loginResponse = http.post(`${BASE_URL}/users/login`, loginPayload, {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
  });

  if (loginResponse.status !== 200) {
    errorRate.add(1);
    console.log(`创建课程失败: 登录失败, 状态码: ${loginResponse.status}`);
    return;
  }

  let userId;
  try {
    const loginBody = JSON.parse(loginResponse.body);
    userId = loginBody.userId;
  } catch (e) {
    errorRate.add(1);
    console.log('创建课程失败: 无法解析登录响应');
    return;
  }

  // 生成课程数据
  const newCourse = generateRandomCourse();
  
  // 构造创建课程的请求payload
  const createCoursePayload = {
    courses: newCourse,
    userId: userId
  };

  const createResponse = http.post(`${BASE_URL}/courses/createCourse`, JSON.stringify(createCoursePayload), {
    headers: {
      'Content-Type': 'application/json',
    },
  });

  const createSuccess = check(createResponse, {
    '创建课程状态码为201': (r) => r.status === 201,
    '创建课程响应时间 < 1000ms': (r) => r.timings.duration < 1000,
    '返回创建的课程信息': (r) => {
      try {
        const body = JSON.parse(r.body);
        return body && body.courseId === newCourse.courseId;
      } catch (e) {
        return false;
      }
    },
  });

  if (!createSuccess) {
    errorRate.add(1);
    console.log(`创建课程失败: ${newCourse.courseId}, 状态码: ${createResponse.status}, 响应: ${createResponse.body}`);
  } else {
    errorRate.add(0);
    console.log(`成功创建课程: ${newCourse.courseName} (${newCourse.courseId})`);
  }

  return createResponse;
}

// 主测试函数
export default function () {
  // 随机选择要执行的测试
  const testType = Math.floor(Math.random() * 4);
  
  switch (testType) {
    case 0:
      console.log('执行用户登录测试');
      testUserLogin();
      break;
    case 1:
      console.log('执行获取课程测试');
      testGetAllCourses();
      break;
    case 2:
      console.log('执行用户注册测试');
      testUserRegister();
      break;
    case 3:
      console.log('执行创建课程测试');
      testCreateCourse();
      break;
  }

  // 模拟用户思考时间
  sleep(Math.random() * 2 + 1); // 1-3秒随机等待
}

// 测试设置函数
export function setup() {
  console.log('开始k6压力测试...');
  console.log(`测试目标: ${BASE_URL}`);
  console.log('测试接口:');
  console.log('1. POST /api/users/login - 用户登录');
  console.log('2. GET /api/courses - 获取所有课程');
  console.log('3. POST /api/users/register - 用户注册');
  console.log('4. POST /api/courses/createCourse - 创建课程');
  console.log('测试用户: teacher001/teacher123, student001/student123');
  return {};
}

// 测试结束函数
export function teardown(data) {
  console.log('k6压力测试完成!');
}